package com.myblog.controller;

import com.myblog.common.ResultInfoFactory;
import com.myblog.model.po.Article;
import com.myblog.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 
 * @since 2022-09-05
 */
@Controller
@RequestMapping("/article")
public class ArticleController {

    private static final String HTML_PREFIX="admin/article/";

    @Autowired
    private ArticleService articleService;

    @GetMapping(value = {"/",""})
    public String article(){
        return HTML_PREFIX+"article-list";
    }

    @PreAuthorize("hasAuthority('sys:article:list')")
    @ResponseBody
    @PostMapping("/list")
    public ResultInfoFactory list(){
        List<Article> list = articleService.list();
        return ResultInfoFactory.success(list);
    }


    @PreAuthorize("hasAnyAuthority('sys:article:add','sys:article:edit')")
    @GetMapping(value = {"/form","/form/{id}"})
    public String form(@PathVariable(required = false)Long id, Model model){
        if(id==null){
            model.addAttribute("article",new Article());
        }else {
            Article article = articleService.getById(id);
            model.addAttribute("article",article);
        }
        return HTML_PREFIX+"article-form";
    }
    @PreAuthorize("hasAnyAuthority('sys:article:add','sys:article:edit')")
    @RequestMapping(value = {"/saveOrUpdate"},method = {RequestMethod.POST,RequestMethod.PUT})
    public String saveOrUpdate(Article article){
        //log.info(sysRole.toString());
        articleService.saveOrUpdate(article);
        return "redirect:/article";
    }

    @PreAuthorize("hasAuthority('sys:article:delete')")
    @DeleteMapping("/{id}")
    @ResponseBody
    public ResultInfoFactory deleteById(@PathVariable("id") Long id){
        articleService.removeById(id);
        return ResultInfoFactory.success();
    }


}
